<?php
class TdMySQLBind extends TdPersistent {
  private $db;
  private $sqlload;
  private $sqlloadargs;
  private $sqlsave;
  private $sqlsaveargs;
  private $sqlcreate;
  private $sqlcreateargs;
  private $sqldelete;
  private $sqldeleteargs;
  private $fields;
  
	function __construct($pk, $instance) {
		parent::__construct($pk);
		
		$this->db = new TdMySql($instance);
	}
	
	function __destruct() {
		$this->db->close();
	}

	function load() {
		if (isset($this->sqlload)) {
			$args = array();
			foreach ($this->sqlloadargs as $field) {
				$args[] = $this->getField($field);
			}
			$params = array_merge(array($this->sqlload), $args);			
			
			$sql = call_user_func_array("sprintf", $params);			
			
			$res = $this->db->select($sql);			
			
		  $this->setFields($res[0]);			  
		  parent::save();
		}
		else {
			return false;
		}
	}
	
	function create() {
		$res = false;
		
		if (isset($this->sqlcreate)) {
			$args = array();
			foreach ($this->sqlcreateargs as $field) {
				$args[] = $this->getField($field);
			}
			$params = array_merge(array($this->sqlcreate), $args);
			$sql = call_user_func_array("sprintf", $params);
		  if ($this->db->insert($sql)) {
		  	$this->load();
		  	parent::save();
		  	$res = true;
		  }
		}

	  return $res;
	}

	function save() {
		if (isset($this->sqlsave)) {
			$args = array();
			foreach ($this->sqlsaveargs as $field) {
				$args[] = $this->getField($field);
			}
			$params = array_merge(array($this->sqlsave), $args);
			$sql = call_user_func_array("sprintf", $params);
		  $this->db->update($sql);
			parent::save();
		}
		else {
			return false;
		}
	}
	
	function delete() {
		if (isset($this->sqldelete)) {
			$args = array();
			foreach ($this->sqldeleteargs as $field) {
				$args[] = $this->getField($field);
			}
			$params = array_merge(array($this->sqldelete), $args);
			$sql = call_user_func_array("sprintf", $params);
		  $this->db->delete($sql);
			parent::delete();
		}
		else {
			return false;
		}
	}
	
	function setLoadSQL($value, $args = null) {
		$this->sqlload = $value;
		$this->sqlloadargs = $args;
	}
	
	function setCreateSQL($value, $args = null) {
		$this->sqlcreate = $value;
		$this->sqlcreateargs = $args;
	}
	
	function setSaveSQL($value, $args = null) {
		$this->sqlsave = $value;
		$this->sqlsaveargs = $args;
	}
	
	function setDeleteSQL($value, $args = null) {
		$this->sqldelete = $value;
		$this->sqldeleteargs = $args;
	}
		
	function setFields($value) {
		$this->fields = $value;		
	}
	function getFields() {
		return $this->fields;
	}
	
	function setField($name, $value) {
		$this->fields[$name] = $value;		
	}
	function getField($name) {
		return (isset($this->fields[$name])) ? $this->fields[$name] : false;
	}
}